<template>
  <div class="rev-table">
    <div class="rev-card el-card el-card__body">
      <div class="main-table">
        <meta-table
          ref="metaTableRef"
          v-model:selection="multipleSelection"
          :meta="state.columns"
          :list="state.tableData"
          :showSelect="true"
        />
      </div>
    </div>
    <div class="bottom-btns">
      <el-button @click="closeDialog()">取消</el-button>
      <el-button type="primary" @click="doSave()">确定</el-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref, getCurrentInstance } from 'vue'
import { getTableMeta, getTableList } from '@/api/basic'
import { getUserRole, updateUserRole } from '@/api/basic/admin'
import { MetaTable } from '@/modules/meta'

const props = defineProps({
  data: {
    type: Object,
    default: () => ({})
  },
  meta: {
    type: Array,
    default: () => []
  },
  onClose: {
    type: Function
  }
})

const state: any = reactive({
  query: {
    page: 1,
    size: 999
  },
  conditions: {},
  source: 'table/sys_role.yaml',
  columns: [],
  config: {},
  orderBy: '',
  tableData: [],
  order: ''
})
const metaTableRef = ref()
// 查询meta
const queryTableMeta = () => {
  getTableMeta({
    source: state.source
  }).then((res: any) => {
    state.columns = res.fields
  })
}
// 获取数据
const getList = async () => {
  const res: any = await getTableList({
    as_dict: true,
    ...state.query,
    conditions: state.conditions,
    source: state.source,
    filter: state.config?.filter,
    order: state.orderBy
  })
  state.tableData = res.data
}
const multipleSelection = ref([])

const fetchUserRole = () => {
  getUserRole({ user_id: props.data.id }).then(async (res) => {
    const selectedRoles = res.data.map((x: any) => ({ id: Number(x) }))
    await getList()
    // multipleSelection.value = selectedRoles
    metaTableRef.value.setSelection(selectedRoles, true)
  })
}

const init = () => {
  queryTableMeta()
  fetchUserRole()
}

onMounted(() => {
  init()
})

const instance = getCurrentInstance() as any
const { proxy } = instance
const closeDialog = () => {
  if (typeof props.onClose === 'function') {
    props.onClose()
  }
  proxy.$parent.$parent.$parent.$parent.$parent.handleClose()
}

const doSave = () => {
  updateUserRole({
    user_id: props.data?.id,
    role_ids: multipleSelection.value?.map((r: any) => r.id)
  }).then(() => {
    closeDialog()
  })
}
</script>
<style lang="less" scoped>
.rev-table {
  height: 80vh;
  display: flex;
  flex-direction: column;

  .rev-card {
    flex: 1;
    display: flex;
  }
  .main-table {
    flex: 1;
  }
  .bottom-btns {
    text-align: right;
    margin-top: 10px;
  }
}
</style>
